package com.jsc.common.utils.httputils;

import com.alibaba.fastjson.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.net.ProtocolException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * http通讯接口
 */
@Slf4j
public class HttpSendRequest {


    /**
     * @param urlStr http请求路径
     * @param params 请求参数
     * @param images 上传文件
     * @return
     */
    public static InputStream post(String urlStr, Map<String, String> params,
                                   Map<String, File> images) {
        String BOUNDARY = "-------45962402127348";
        String FILE_ENCTYPE = "multipart/form-data";
        InputStream is = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            con.setConnectTimeout(5000);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", FILE_ENCTYPE + "; boundary="
                    + BOUNDARY);

            StringBuilder sb = null;
            DataOutputStream dos = new DataOutputStream(con.getOutputStream());
            if (params != null) {
                sb = new StringBuilder();
                for (String s : params.keySet()) {
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append(s);
                    sb.append("\"\r\n\r\n");
                    sb.append(params.get(s));
                    sb.append("\r\n");
                }

                dos.write(sb.toString().getBytes());
            }

            if (images != null) {
                for (String s : images.keySet()) {
                    File f = images.get(s);
                    sb = new StringBuilder();
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append("file");
                    sb.append("\"; filename=\"");
                    sb.append(f.getName());
                    sb.append("\"\r\n");
                    sb.append("Content-Type: application/zip");//这里注意！如果上传的不是图片，要在这里改文件格式，比如txt文件，这里应该是text/plain
                    sb.append("\r\n\r\n");
                    dos.write(sb.toString().getBytes());

                    FileInputStream fis = new FileInputStream(f);
                    byte[] buffer = new byte[(int) f.length()];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, len);
                    }
                    dos.write("\r\n".getBytes());
                    fis.close();
                }

                sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("--\r\n");
                dos.write(sb.toString().getBytes());
            }
            dos.flush();


            is = con.getInputStream();

            dos.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }


    public static Map sendMultiFormMixData(String url, String filePaths, String data) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        SSLClient client = new SSLClient();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        ContentBody fileBody = new FileBody(new File(filePaths), ContentType.MULTIPART_FORM_DATA);
        builder.addPart("guarantee_file", fileBody);
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        Map<String, String> messMap = JSON.parseObject(data, Map.class);
        for (Map.Entry<String, String> entry : messMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            builder.addPart(key, new StringBody(value, contentType));
        }
        HttpEntity httpEntity = builder.build();
        httpPost.setEntity(httpEntity);
        HttpResponse response = client.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("发送状态为：" + statusCode);
        int statusCodeHttp = response.getStatusLine().getStatusCode();
        if (statusCodeHttp == HttpStatus.SC_OK  ) {
            String jsonData = EntityUtils.toString(response.getEntity(), "UTF-8");
            map.put("sendStatus", "200");
            map.put("sendMess", jsonData);
        } else {
            map.put("sendStatus", "500");
            map.put("sendMess", "发送失败");
        }
        return map;
    }


    public static String doPost(String url, String param) {

        HttpPost httpPost = null;
        String result = null;
        try {
            SSLClient client = new SSLClient(); // 支持 https
//            HttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param, "utf-8");
                httpPost.setEntity(se); // post方法中，加入json数据
                httpPost.setHeader("Content-Type", "application/json");
            }

            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }

        } catch (Exception ex) {
            log.error("发送到接口出错", ex);
        }
        return result;
    }


}
